//
//  RiskCheckCenter.js
//  SugLisSystem
//  校验险种信息
//  Created by Mr.Right on 2013-04-02.
//  Copyright 2013 Mr.Right. All rights reserved.
//

var dB = require('untils/DB');
var exeSQL = require('untils/ExeSQL');
var pubFun = require('untils/PubFun')
var extFeeCaculator = require('corecenter/ExtFeeCaculator');
var riskPol = require('suggest/RiskPol');
var tGlobalInput = require('GlobalInput');

function checkForOnePol(mainPolNo, flagStr) {
	var infoList = riskPol.getPolList(mainPolNo, '', 1, false);
	var polList = infoList[1];
	var contNo = '';
	var flag = true;
	var finalFlag = (flagStr == 'FINAL');

	var evalParam = null;

	var errorSet = [];
	var toolTipSet = [];
	Ti.API.warn('[RiskCheckCenter]本次校验险种个数：' + polList.length);
	for (var m = 0; m < polList.length; m++) {
		var remLSPolSchema = polList[m];
		contNo = remLSPolSchema['contno'];
		var rePolElementSchema = initPolElementSchemaInfo(remLSPolSchema['polno']);
		// 算法集合
		var inLMCalModeSet = getAllCalSet(rePolElementSchema['RiskCode'], true, true, finalFlag);
		//获取错误列表
		var sexAgeError = checkSexAndAge(rePolElementSchema);
		var occuptionPremAmntError = checkOccupationAndPrem(rePolElementSchema);
		var riskSpecialRulesError = checkRiskSpecialRules(rePolElementSchema, inLMCalModeSet, evalParam);
		var commonRulesError = checkCommonRules(rePolElementSchema, inLMCalModeSet, evalParam);
		Ti.API.warn('[RiskCheckCenter]年龄性别校验错误' + sexAgeError.length + '条');
		for (var i = 0; i < sexAgeError.length; i++) {
			errorSet.push(sexAgeError[i]);
		}
		Ti.API.warn('[RiskCheckCenter]职业保费校验错误' + occuptionPremAmntError.length + '条');
		for (var i = 0; i < occuptionPremAmntError.length; i++) {
			errorSet.push(occuptionPremAmntError[i]);
		}
		Ti.API.warn('[RiskCheckCenter]特殊规则校验错误' + riskSpecialRulesError.errorSet.length + '条');
		for (var i = 0; i < riskSpecialRulesError.errorSet.length; i++) {
			errorSet.push(riskSpecialRulesError.errorSet[i]);
		}
		Ti.API.warn('[RiskCheckCenter]通用规则校验错误' + commonRulesError.errorSet.length + '条');
		for (var i = 0; i < commonRulesError.errorSet.length; i++) {
			errorSet.push(commonRulesError.errorSet[i]);
		}
		if (finalFlag) {
			var finalCheckError = finalCheckForALl(rePolElementSchema, inLMCalModeSet, evalParam);
			//TODO 貌似重复错误的可能行，如果重复，修改或则直接删除
			Ti.API.warn('[RiskCheckCenter]最终规则校验错误' + finalCheckError.errorSet.length + '条');
			for (var i = 0; i < finalCheckError.errorSet.length; i++) {
				errorSet.push(finalCheckError.errorSet[i]);
			}
			for (var i = 0; i < finalCheckError.toolTipSet.length; i++) {
				toolTipSet.push(finalCheckError.toolTipSet[i]);
			}
		}
	}

	Ti.API.warn('[RiskCheckCenter]出错提示' + errorSet.length + '条');
	for (var i = 0; i < errorSet.length; i++) {
		Ti.API.warn('[RiskCheckCenter]' + (i + 1) + '.' + errorSet[i]);
	}
	Ti.API.warn('[RiskCheckCenter]温馨提示' + toolTipSet.length + '条');
	var reslut = {
		toolTipSet : toolTipSet,
		errorSet : errorSet
	}

	return reslut;
}

exports.checkForOnePol = checkForOnePol;
/**
 * 初始化校验数据
 * @param polNo
 */
function initPolElementSchemaInfo(polNo) {
	var inPolElementSchema = {};
	// 管理机构
	inPolElementSchema['ManageCom'] = tGlobalInput['ComCode'];
	// 销售渠道
	inPolElementSchema['RiskChannel'] = tGlobalInput['chanlesign'];
	// 代理人号
	inPolElementSchema['AgentCode'] = tGlobalInput['Operator'];

	//POL表中信息
	var reLSPolDB = new dB('LSPol');
	reLSPolDB['polno'] = polNo;
	reLSPolDB.getInfo();
	inPolElementSchema['ContNo'] = reLSPolDB['contno']
	inPolElementSchema['RiskCode'] = reLSPolDB['riskcode'];
	inPolElementSchema['Amnt'] = reLSPolDB['amnt'];
	inPolElementSchema['Get'] = reLSPolDB['amnt'];
	inPolElementSchema['Prem'] = reLSPolDB['prem'];
	inPolElementSchema['Mult'] = reLSPolDB['mult'];
	inPolElementSchema['BonusGetMode'] = reLSPolDB['bonusgetmode'];
	inPolElementSchema['LiveGetMode'] = reLSPolDB['livegetmode'];
	inPolElementSchema['GetYear'] = reLSPolDB['getyear'];
	inPolElementSchema['GetYearFlag'] = reLSPolDB['getyearflag'];
	inPolElementSchema['InsuYear'] = reLSPolDB['insuyear'];
	inPolElementSchema['InsuYearFlag'] = reLSPolDB['insuyearflag'];
	inPolElementSchema['PayEndYear'] = reLSPolDB['payendyear'];
	inPolElementSchema['PayEndYearFlag'] = reLSPolDB['payendyearflag'];
	inPolElementSchema['PayIntv'] = reLSPolDB['payintv'];
	inPolElementSchema['StandbyFlag1'] = reLSPolDB['standbyglag1'];
	inPolElementSchema['StandbyFlag2'] = reLSPolDB['standbyglag2'];
	inPolElementSchema['StandbyFlag3'] = reLSPolDB['standbyglag3'];
	inPolElementSchema['SubRiskFlag'] = reLSPolDB['subflag'];
	inPolElementSchema['PolNo'] = reLSPolDB['polno'];
	inPolElementSchema['MainPolNo'] = reLSPolDB['mainpolno'];
	inPolElementSchema['Years'] = reLSPolDB['years'];
	inPolElementSchema['PayYears'] = reLSPolDB['payyears'];
	inPolElementSchema['StandardPrem'] = reLSPolDB['standardprem'];

	//计算主险保费
	var mainRiskAmntSQL = "SELECT Amnt FROM LSPOL WHERE POLNO ='" + reLSPolDB['mainpolno'] + "'";
	var mainRiskAmnt = exeSQL.getOneValue(mainRiskAmntSQL);
	if (mainRiskAmnt != null) {
		inPolElementSchema['MainPolAmnt'] = mainRiskAmnt;
	}

	// 投保人信息
	var LsAppntDB = new dB('LsAppnt');
	LsAppntDB['contno'] = reLSPolDB['contno'];
	if (LsAppntDB.getInfo()) {
		// 投保人号
		inPolElementSchema['AppntNo'] = LsAppntDB['appntno'];
		//投保人生日
		inPolElementSchema['AppntBirthday'] = LsAppntDB['appntbirthday'];
		// 投保人年龄
		if (LsAppntDB['appntage'] == null) {
			inPolElementSchema['AppntAge'] = pubFun.calInterval(LsAppntDB['appntbirthday'], pubFun.getCurrentDate(), 'Y');
		} else {
			inPolElementSchema['AppntAge'] = LsAppntDB['appntage'];
		}
		// 投保人性别
		inPolElementSchema['AppntSex'] = LsAppntDB['appntsex'];
		// 职业代码
		inPolElementSchema['AppntOccupationCode'] = LsAppntDB['appntoccupationcode'];
		// 国籍代码
		inPolElementSchema['AppntNativePlace'] = LsAppntDB['nativeplace'];
	}

	// 被保人信息
	var reLSInsuredDB = new dB('LSInsured');
	reLSInsuredDB['contno'] = reLSPolDB['contno'];
	reLSInsuredDB['insuredno'] = reLSPolDB['insuredno'];
	if (reLSInsuredDB.getInfo()) {
		// 被保人号
		inPolElementSchema['InsuredNo'] = reLSInsuredDB['insuredno'];
		// 被保人姓名
		inPolElementSchema['Name'] = reLSInsuredDB['name'];
		// 被保人出生日期
		inPolElementSchema['Birthday'] = reLSInsuredDB['birthday'];
		// 被保人年龄
		if (reLSInsuredDB['age'] == null) {
			inPolElementSchema['AppAge'] = pubFun.calInterval(reLSInsuredDB['birthday'], pubFun.getCurrentDate(), 'Y');
		} else {
			inPolElementSchema['AppAge'] = reLSInsuredDB['age'];
		}

		// 被保人性别
		inPolElementSchema['Sex'] = reLSInsuredDB['sex'];
		// 被保人职业代码
		inPolElementSchema['OccupationCode'] = reLSInsuredDB['occupationcode'];
		// 被保人国籍代码
		inPolElementSchema['InsuredNativePlace'] = reLSInsuredDB['insurednativeplace'];
		// 被保人与投保人关系
		inPolElementSchema['RelationToAppnt'] = reLSInsuredDB['relationtoappnt'];
	}

	// 计算累计风险保额
	calSumRiskAmnt(inPolElementSchema);

	// 家庭计划
	inPolElementSchema['PolTypeFlag'] = reLSPolDB['poltypeflag'];
	inPolElementSchema['Remark'] = reLSPolDB['remark'];
	inPolElementSchema['PlanNodeCode'] = reLSPolDB['agentype'];

	return inPolElementSchema;
}

/**
 * 计算各种累计风险保额数据
 * @param inPolElementSchema 校验数据
 */
function calSumRiskAmnt(inPolElementSchema) {
	var reLMRiskParasDB = new dB('LMRiskParam');
	reLMRiskParasDB['type'] = 'RiskAmnt';
	var reLMRiskParamSet = reLMRiskParasDB.query(); String
	sql = "Select * From LSPol Where ContNo='" + inPolElementSchema['ContNo'] + "' and insuredNo='" + inPolElementSchema['InsuredNo'] + "'";
	var LSPolDB = new dB('LSPol');
	var reLSPolSet = LSPolDB.executeQuery(sql);

	// 各种类型的保额
	var type_Life = "Life";
	var type_Acc = "Acc";
	var type_Dea = "Dea";
	var type_Duty = "DeaDuty";
	// 未成年人保额
	var type_Child = "Child";
	// 体检保额
	var type_BdCk = "BdCk";
	// 财务保额
	var type_Fin = "Fin";
	// 一般保额
	var type_Comon = "Comon";
	// 其他类型的保额
	var type_Bod = "Bod";

	inPolElementSchema['SumLifeRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Life);
	inPolElementSchema['SumAccRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Acc);
	inPolElementSchema['SumDeaRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Dea);
	inPolElementSchema['SumDeaDutyRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Duty);
	inPolElementSchema['SumChildRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Child);
	inPolElementSchema['SumBdCkRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_BdCk);
	inPolElementSchema['SumFinRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Fin);
	inPolElementSchema['SumComonRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Comon);
	inPolElementSchema['SumBodRiskAmnt'] = calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type_Bod);
	return inPolElementSchema;
}

/**
 * 计算单项风险保额
 *
 * @param reLMRiskParamSet 参数表数据
 * @param reLSPolSet Pol表数据
 * @param type 风险保额类型
 */
function calRiskAmntByType(reLMRiskParamSet, reLSPolSet, type) {
	var riskAmntList = [];
	for (var i = 0; i < reLMRiskParamSet.length; i++) {
		var tempLMRiskParamSchema = reLMRiskParamSet[i];
		var param = tempLMRiskParamSchema['param'];
		if (type == param) {
			riskAmntList.push(tempLMRiskParamSchema);
		}
	}
	var riskAmnt = 0;
	// 逐一保单进行计算
	for (var i = 1; i < reLSPolSet.length; i++) {
		var teLSPolSchema = reLSPolSet[i];
		// 处理
		var tempLMRiskParamSchema = getRelaRiskParamSchema(teLSPolSchema['riskcode'], type, riskAmntList);
		if (tempLMRiskParamSchema != null) {
			riskAmnt += getValueOfRiskAmntForOnePol(tempLMRiskParamSchema, type, teLSPolSchema);
		}
	}
	Ti.API.warn('[RiskCheckCenter]计算风险保费' + type + ':' + riskAmnt);
	return riskAmnt;
}

function getRelaRiskParamSchema(riskCode, type, list) {
	var reLMRiskParamSchema = null;
	for (var i = 0; i < list.length; i++) {
		var tempLMRiskParamSchema = list[i];
		if (type == tempLMRiskParamSchema['param'] && riskCode == tempLMRiskParamSchema['riskcode']) {
			reLMRiskParamSchema = tempLMRiskParamSchema;
			break;
		}
	}
	return reLMRiskParamSchema;
}

function getValueOfRiskAmntForOnePol(inreLMRiskParamSchema, type, inLSPolSchema) {
	var result = 0;
	if (inreLMRiskParamSchema != null) {
		var expression = inreLMRiskParamSchema['expression'];
		result = calRiskAmntByExpress(expression, inLSPolSchema);
	}
	return result;
}

function calRiskAmntByExpress(expression, reLSPolShcema) {
	var AppAge = reLSPolShcema['insuredappage'];
	var ContNo = reLSPolShcema['contno'];
	var InsuredNo = reLSPolShcema['insuredno'];
	var PolNo = reLSPolShcema['polno'];
	var Amnt = reLSPolShcema['amnt'];
	var Get = reLSPolShcema['amnt'];
	var Prem = reLSPolShcema['prem'];
	var Mult = reLSPolShcema['mult'];
	var PayIntv = reLSPolShcema['payintv'];
	var InsuYear = reLSPolShcema['insuyear'];
	var InsuYearFlag = reLSPolShcema['insuyearflag'];
	var PayEndYear = reLSPolShcema['payendyear'];
	var PayEndYearFlag = reLSPolShcema['payendyearflag'];
	var LiveGetMode = reLSPolShcema['livegetmode'];
	var StandbyFlag1 = reLSPolShcema['standbyflag1'];
	var StandbyFlag2 = reLSPolShcema['standbyflag2'];
	var StandbyFlag3 = reLSPolShcema['standbyflag3'];
	return eval(expression);
}

/**
 * 获取所有算法
 *
 * @param riskcode
 * @param isUI
 * @param isTBINSERT
 * @param isFINAL
 */
function getAllCalSet(riskCode, isUI, isTBINSERT, isFINAL) {
	var fieldNameCondition = "''";
	if (isUI) {
		fieldNameCondition += ",'UI'";
	};
	if (isTBINSERT) {
		fieldNameCondition += ",'TBINSERT'";
	}
	if (isFINAL) {
		fieldNameCondition += ",'FINAL','TOOLTIP'";
	}

	fieldNameCondition = " AND FIELDNAME IN (" + fieldNameCondition + ")";

	var calsql = "SELECT * FROM LMCALMODE WHERE CALCODE IN (SELECT CALCODE FROM LMCHECKFIELD WHERE RISKCODE IN ('" + riskCode + "','000000')" + fieldNameCondition + ")";

	var LMCalModeDB = new dB('LMCalMode');
	return LMCalModeDB.executeQuery(calsql);
}

/**
 * 校验投被保人性别，年龄 渠道
 * @param inPolElementSchema 数据集合
 * @return 错误信息
 */
function checkSexAndAge(inPolElementSchema) {
	var riskCode = inPolElementSchema['RiskCode'];
	var appntBirthday = inPolElementSchema['AppntBirthday'];
	var insuredBirthday = inPolElementSchema['Birthday'];
	var appntAge = inPolElementSchema['AppntAge'];
	var insuredAge = inPolElementSchema['Age'];
	var appntSex = inPolElementSchema['AppntSex'];
	var insuredSex = inPolElementSchema['AppAge'];

	//年龄
	if (appntAge == null) {
		appntAge = pubFun.calInterval(appntBirthday, pubFun.getCurrentDate(), 'Y');
	}
	if (insuredAge == null) {
		insuredAge = pubFun.calInterval(insuredBirthday, pubFun.getCurrentDate(), 'Y');
	}
	//渠道
	var manageCom = inPolElementSchema['ManageCom'];
	var chanle = inPolElementSchema['RiskChannel'];
	var RiskPlanAndRiskSaleConfDB = new dB('RiskPlanAndRiskSaleConf');
	RiskPlanAndRiskSaleConfDB['riskandriskplancode'] = inPolElementSchema['RiskCode'];
	var RiskPlanAndRiskSaleConfSet = RiskPlanAndRiskSaleConfDB.query();

	var channelSet = [];
	var errorSet = [];

	var currentDate = pubFun.getCurrentDate();
	for (var i = 0; i < RiskPlanAndRiskSaleConfSet.length; i++) {
		var reRiskPlanAndRiskSaleConfSchema = RiskPlanAndRiskSaleConfSet[i];
		// 渠道
		var checkType = reRiskPlanAndRiskSaleConfSchema['type'];
		var checkValue = reRiskPlanAndRiskSaleConfSchema['value1'];
		if ('Chanle' == checkType) {
			channelSet.push(checkValue);
		}
		// 地区
		if ('ManageComGrpCode' == checkType && !checkComCodeGrp(checkValue, manageCom)) {
			errorSet.push('[' + riskCode + ']险种销售地区与当前地区不符');
		}
		// 开始销售日期
		if ('StartDate' == checkType && pubFun.getLaterDate(checkValue, currentDate) == checkValue) {
			errorSet.push('[' + riskCode + ']当前日期不在险种销售日期范围内');
		}
		// 结束销售日期
		if ('EndDate' == checkType && pubFun.getBeforeDate(checkValue, currentDate) == checkValue) {
			errorSet.push('[' + riskCode + ']当前日期不在险种销售日期范围内');
		}
		//年龄标记
		var ageMark = {
			'Y' : '岁',
			'M' : '月',
			'D' : '天'
		}
		// 投保人年龄
		if ('AppAgeMax' == checkType) {
			var checkValue_amax = reRiskPlanAndRiskSaleConfSchema['value2'];
			var checkAge = pubFun.calInterval(appntBirthday, currentDate, checkValue_amax);
			if (checkAge > checkValue) {
				errorSet.push('[' + riskCode + ']投保人的年龄[' + checkAge + ageMark[checkValue_amax] + ']大于险种要求的最大年龄[' + checkValue + ageMark[checkValue_amax] + ']');
			}
		}
		// 被保人年龄
		if ('InsuAgeMax' == checkType) {
			var checkValue_imax = reRiskPlanAndRiskSaleConfSchema['value2'];
			var checkAge = pubFun.calInterval(insuredBirthday, currentDate, checkValue_imax);
			if (checkAge > checkValue) {
				errorSet.push('[' + riskCode + ']被保人的年龄[' + checkAge + ageMark[checkValue_imax] + ']大于险种要求的最大年龄[' + checkValue + ageMark[checkValue_imax] + ']');
			}
		}
		if ('InsuAgeMin' == checkType) {
			var checkValue_imin = reRiskPlanAndRiskSaleConfSchema['value2'];
			var checkAge = pubFun.calInterval(insuredBirthday, currentDate, checkValue_imin);
			if (checkAge < checkValue) {
				errorSet.push('[' + riskCode + ']被保人的年龄[' + checkAge + ageMark[checkValue_imin] + ']小于险种要求的最小年龄[' + checkValue + ageMark[checkValue_imin] + ']');
			}
		}

		//性别
		if ('AppSex' == checkType && checkValue != appntSex) {
			errorSet.push('[' + riskCode + ']投保人的性别不符合险种的特定需要');
		}
		if ('InsuSex' == checkType && checkValue != insuredSex) {
			errorSet.push('[' + riskCode + ']被保人的性别不符合险种的特定需要');
		}
	}

	//渠道
	if (channelSet.indexOf(chanle) == -1) {
		errorSet.push('[' + riskCode + ']险种销售渠道与当前渠道不符');
	}
	return errorSet;
}

/**
 * 职业保费保额校验
 * @param inPolElementSchema
 * @return 校验错误信息
 * */
function checkOccupationAndPrem(inPolElementSchema) {
	var errorSet = [];
	var occupationCode = inPolElementSchema['OccupationCode'];
	var riskCode = inPolElementSchema['RiskCode'];
	var LMRiskAppDB = new dB('LMRiskApp');
	LMRiskAppDB['riskcode'] = riskCode;
	LMRiskAppDB.getInfo();
	var riskType = LMRiskAppDB['risktype'];
	var riskProp = LMRiskAppDB['riskprop'];
	// 检查是否为豁免险
	if ('R' == riskProp) {
		// 需要重新分配
		occupationCode = inPolElementSchema['AppntOccupationCode'];
	}

	if (extFeeCaculator.checkRefuse(riskCode, occupationCode)) {
		errorSet.push('[' + riskCode + ']系统拒保当前职业[' + occupationCode + ']');
	}
	var sql = "select * from lmdutypay where PayPlanCode in (select payplancode from LMDutyPayRela where dutycode in (select dutycode from lmriskduty where riskcode='" + riskCode + "'))";
	var LMDutyPayDB = new dB('LMDutyPay');
	var LMDutyPaySet = LMDutyPayDB.executeQuery(sql);
	if (LMDutyPaySet.length > 0) {
		var zeroFlag = LMDutyPaySet[0]['zeroflag'];
		if (zeroFlag == 'N' && inPolElementSchema['Prem'] == 0) {
			errorSet.push('[' + riskCode + ']计算出来的保费不能为0,请检查缴费期与被保险人年龄是否匹配或被保险人职业等级是否超过限制');
		}
	}

	sql = "select * from lmdutyget where getdutycode in (select getdutycode from LMDutygetRela where dutycode in (select dutycode from lmriskduty where riskcode='" + riskCode + "'))";
	var LMDutyGetDB = new dB('LMDutyGet');
	var LMDutyGetSet = LMDutyGetDB.executeQuery(sql);
	if (LMDutyGetSet.length > 0) {
		var zeroFlag = LMDutyGetSet[0]['zeroflag'];
		if (zeroFlag == 'N' && inPolElementSchema['Amnt'] == 0) {
			errorSet.push('[' + riskCode + ']计算出来的保额不能为0,请检查缴费期与被保险人年龄是否匹配或被保险人职业等级是否超过限制');
		}
	}
	return errorSet;
}

/**
 * 特殊校验校验
 * @param inPolElementSchema
 * @param inLMCalModeSet
 * @param evalParam
 * */
function checkRiskSpecialRules(inPolElementSchema, inLMCalModeSet, evalParam) {
	var reslut = {
		toolTipSet : [],
		errorSet : []
	};
	var LMCheckFieldDB = new dB('LMCheckField');
	var sql = "Select * From LMCheckField Where RiskCode = '" + inPolElementSchema['RiskCode'] + "' and FieldName='TBINSERT' order by SerialNo";
	var LMCheckFieldSet = LMCheckFieldDB.executeQuery(sql);
	for (var i = 0; i < LMCheckFieldSet.length; i++) {
		checkAction(reslut, inLMCalModeSet, LMCheckFieldSet[i], inPolElementSchema, evalParam);
	}
	return reslut;
}

/**
 * 通用校验规则
 * @param inPolElementSchema
 * @param inLMCalModeSet
 * @param evalParam
 * */
function checkCommonRules(inPolElementSchema, inLMCalModeSet, evalParam) {
	var reslut = {
		toolTipSet : [],
		errorSet : []
	};
	var LMCheckFieldDB = new dB('LMCheckField');
	var sql = "Select * From LMCheckField Where RiskCode='000000' and FieldName='TBINSERT' and (Location='" + inPolElementSchema['RiskChannel'] + "' or Location is null) order by SerialNo";
	var LMCheckFieldSet = LMCheckFieldDB.executeQuery(sql);
	for (var i = 0; i < LMCheckFieldSet.length; i++) {
		checkAction(errorSet, inLMCalModeSet, LMCheckFieldSet[i], inPolElementSchema, evalParam);
	}
	return reslut;
}

/**
 * 最后整单校验
 * @param inPolElementSchema
 * @param inLMCalModeSet
 * @param evalParam
 */
function finalCheckForALl(inPolElementSchema, inLMCalModeSet, evalParam) {
	var reslut = {
		toolTipSet : [],
		errorSet : []
	};
	var LMCheckFieldDB = new dB('LMCheckField');
	var sql = "Select * From LMCheckField Where (RiskCode='000000' or RiskCode='" + inPolElementSchema['RiskCode'] + "' ) and (FieldName='FINAL' or FieldName='TOOLTIP') and (Location='" + inPolElementSchema['RiskChannel'] + "' or Location is null) order by SerialNo";
	var LMCheckFieldSet = LMCheckFieldDB.executeQuery(sql);
	for (var i = 0; i < LMCheckFieldSet.length; i++) {
		checkAction(errorSet, inLMCalModeSet, LMCheckFieldSet[i], inPolElementSchema, evalParam);
	}
	return reslut;
}

/**
 * 检验管理机构是否属于指定管理机构组
 * @param comGrp
 * @param comcode
 */
function checkComCodeGrp(comGrp, comCode) {
	var flag = false;
	if (comGrp == '000000') {
		flag = true;
	} else {
		var LDComGrpToComDB = new dB('LDComGrpToCom');
		LDComGrpToComDB['comgrpcode'] = comGrp;
		LDComGrpToComDB['comcode'] = comCode;
		var LDComGrpToComSet = LDComGrpToComDB.query();
		flag = (LDComGrpToComSet.length > 0);
	}

	return flag;
}

/**
 * 校验方法
 * @param reslut
 * @param inLMCalModeSet
 * @param inLMCheckFieldSchema
 * @param inPolElementSchema
 * @param expressionParam
 * */
function checkAction(reslut, inLMCalModeSet, inLMCheckFieldSchema, inPolElementSchema, expressionParam) {
	// 执行标识
	var executeFlag = inLMCheckFieldSchema['updflag'];
	// 反馈值
	var returnValueFlag = inLMCheckFieldSchema['returnvaliflag'];
	// 算法
	var calCode = inLMCheckFieldSchema['calcode'];
	Ti.API.warn('[RiskCheckCenter]执行校验算法:' + calCode);
	// 险种代码
	var riskCode = inLMCheckFieldSchema['riskcode'];
	// 错误类型，Error OR ToolTip
	var errorType = inLMCheckFieldSchema['fieldname'];

	var searchFlag = false;
	var inLMCalModeSchema = null;
	for (var i = 0; i < inLMCalModeSet.length; i++) {
		if (inLMCalModeSet[i]['calcode'] == calCode) {
			inLMCalModeSchema = inLMCalModeSet[i];
			searchFlag = true;
			break;
		}
	}

	if (searchFlag) {
		var expression = inLMCalModeSchema['calsql'];
		// 1、原来的SQL
		if (executeFlag == null || executeFlag == '') {
			expression = transportExpression(expression, inPolElementSchema);
			if (!check(expression)) {
				if (errorType == 'TOOLTIP') {
					reslut.toolTipSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
					Ti.API.warn('[RiskCheckCenter]校验错误，增加温馨提示：' + inLMCheckFieldSchema['msg']);
				} else {
					reslut.errorSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
					Ti.API.warn('[RiskCheckCenter]校验错误，增加错误提示：' + inLMCheckFieldSchema['msg']);
				}
			} else {
				Ti.API.warn('[RiskCheckCenter]校验正确');
			}
		}
		// 2、动态执行，结果返回错误信息
		//TODO 暂不支持
		else if (executeFlag == 'DE' && 'DM' == returnValueFlag) {

		}
		// 3、动态执行，不返回错误信息
		//TODO 暂不支持
		else if (executeFlag == 'DE') {

		}
		// 4、不支持的投保规则
		else {
			if (errorType == 'TOOLTIP') {
				reslut.toolTipSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
			} else {
				reslut.errorSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
			}
		}
	} else {
		if (errorType == 'TOOLTIP') {
			reslut.toolTipSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
		} else {
			reslut.errorSet.push('[' + riskCode + ']' + inLMCheckFieldSchema['msg']);
		}
	}
}

/**
 * 替换sql
 * @param expression 表达式
 * @param inPolElementSchema 替换参数
 * */
function transportExpression(expression, inPolElementSchema) {
	for (var obj in inPolElementSchema) {
		eval("expression = expression.replace(/\\?" + obj + "\\?/g, inPolElementSchema." + obj + ");");
	}
	return expression;
}

/**
 * 校验执行
 * @param sql 执行的sql语句
 */
function check(sql) {
	var reslut = exeSQL.getOneValue(sql);
	return (reslut == null || reslut == 0 || reslut == '');
}

/**
 * 动态执行方法
 * @param param
 * @param expression
 * @param hasReturn
 * */
function evalExpression(param, expression, hasReturn) {
	for (var obj in param) {
		eval('var ' + obj + ' = param.' + obj);
	}
	if (pubFun.isNull(hasReturn)) {
		hasReturn = false;
	}
	eval(expression);
	return null;
}
